Param (
    [Parameter(Mandatory=$false)] [int16]$Days = 14
)
#
# The list of accounts, which profiles must not be deleted anyway:
$ExcludedUsers = "Public","Administrator","adm.markov.se","adm.leonov.ay"

Write-Output "Usage (in admin's powershell): .\DelNotUsed.ps1 [-Days {int}]]"
Write-Output "Defaults: Days=14.`n"

Write-Host "Checking for elevated permissions..."
if (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(`
[Security.Principal.WindowsBuiltInRole] "Administrator")) {
    Write-Warning "Insufficient permissions to run this script. Open the PowerShell console as an administrator and run this script again.`n"
    pause
    Break
    # Start-Process Powershell -ArgumentList $PSCommandPath -Verb RunAs
}else{
    Write-Output "Permissions are OK.`n"
}

Write-Output "Finding profiles which older than $Days days ..." 

# Получение объектов (профилей) через вызов Get-WMIObject (которые не специальные и не зарегистрированны сейчас, и регистрировались более $days дней назад):
$OldProfiles = Get-WMIObject -class Win32_UserProfile | Where-Object {(!$_.Special) -and (!$_.Loaded) -and ($_.ConvertToDateTime($_.LastUseTime) -lt (Get-Date).AddDays(-$Days))}

# Вариант получения объектов (профилей) через вызов Get-CIMInstance (это "более перспективно" и, например, позволяет использовать напрямую параметр -ComputerName $compname):  
# $OldProfiles = Get-CimInstance -ClassName Win32_UserProfile | Where-Object {(!$_.Special) -and (!$_.Loaded) -and ($_.LastUseTime -lt (Get-Date).AddDays(-$Days))}

$OldProfilesCount = $OldProfiles.Count
Write-Output "Number of founded profiles: $OldProfilesCount"

# Если найдены профили, отвечающие условиям:
if ($OldProfilesCount -gt 0) {
    # Включение индикатора прогресса выполнения:
    $i = 0
    $progress = @{
        Activity = "Delete old profiles..."
        CurrentOperation = "Process folders of profiles"
        PercentComplete = $i
    }

    Write-Output "Start to delete founded profiles..."

    foreach ($OneProfile in $OldProfiles) {
        # Обновление индикатора прогресса выполнения:
        $i++
        [int]$percentage = ($i / $OldProfilesCount) * 100
        $progress.CurrentOperation = $OneProfile.LocalPath
        $progress.PercentComplete = $percentage
        Write-Progress @progress

        if (!($ExcludedUsers -like $OneProfile.LocalPath.Replace("C:\Users\",""))) {
            $OneProfile | Remove-WmiObject
            Write-Host $OneProfile.LocalPath, "profile deleted" -ForegroundColor Magenta
        }else{
            Write-Host $OneProfile.LocalPath, "profile skiped" -ForegroundColor Yellow
        }
    }
}else{
    Write-Warning "Nothing to do."
}
#
Read-Host -Prompt "Press [Enter] to continue."